package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.Collection;

/**
 * Created by abhishekpuri on 10/6/14.
 */
public class Catalog {

    private Collection<Book> books;
    private IOHandler ioHandler;

    public Catalog()
    {
        books = new ArrayList<Book>();
        ioHandler = new IOHandler();
    }
    public Catalog(Collection<Book> bookList)
    {
        this.books = bookList;
        ioHandler = new IOHandler();
    }

    public void printBookList()
    {
        ioHandler.printlnToConsole("Books currently available in library");
        int i=1;
        for(Book book:books) {
            ioHandler.printlnToConsole(i++ + ". " + book.getName() + "\t\t" + book.getAuthorName() + "\t\t" + book.getPublishingDate());
        }
    }

    private Book search(Book book) {
        for(Book curBook:books) {
            if(book.equals(curBook)) {
                return curBook;
            }
        }
        return null;
    }

    public Book searchByName(String name) {
        for(Book book:books) {
            if(book.getName().equals(name))
                return book;
        }
        return null;
    }

    public boolean addBookToCatalog(Book book) {
        if(search(book)==null) {
            books.add(book);
            return true;
        }
        else {
            ioHandler.printlnToConsole("Book already present in catalog");
            return false;
        }
    }

    public boolean deleteBookFromCatalog(String name) {
        Book res = searchByName(name);
        if(res!=null) {
            books.remove(res);
            return true;
        }
        else {
            ioHandler.printlnToConsole("Book not present in the catalog");
            return false;
        }
    }

    public boolean deleteBookFromCatalog(Book book) {
        Book res=search(book);
        if(res!=null) {
            books.remove(res);
            return true;
        }
        else {
            ioHandler.printlnToConsole("Book not present in the catalog");
            return false;
        }
    }

}
